//
//  Image.m
//  BookMaker
//
//  Created by Mathieu Tozer on 22/11/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "Book.h"
#import "Image.h"
#import "Page.h"

#import "CoreData+Additions.h"

@implementation Image

- (NSArray *)pagesArray
{
	return [[self mutableSetValueForKey:@"pages"] allObjects];
}

- (NSString *)path
{
	return [self primitiveValueForKey:@"path"];
}

- (int)nextOrderNumber
{
	NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:NO];
	
	NSArray *pages = [[self pagesArray] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd]];
	if (pages && [pages count] > 0) {
		return [[[pages objectAtIndex:0] valueForKey:@"order"] intValue]+1;
	}
	return 0;
}

- (Page *)newPage
{
	int i = [self nextOrderNumber];
	NSManagedObject *page = [[self managedObjectContext] insertNewObjectOfEntity:@"Page"];
	[(Page*)page setValue:[NSNumber numberWithInt:i] forKey:@"order"];
	return (Page *)page;
}

- (void)addDefaultPagesForBook:(Book *)book
{
	//create a new page object
	Page *page = [self newPage];
	[page setValue:self forKey:@"image"];
	[page setPageRect:[book targetRect]];
	page = [self newPage];
	[page setValue:self forKey:@"image"];
	[page setPageRect:[book targetRect]];
}

- (BOOL)isFirstLoad
{
	BOOL value = [[self primitiveValueForKey:@"isFirstLoad"] boolValue];
	if (value) {
		[self setPrimitiveValue:[NSNumber numberWithBool:NO] forKey:@"isFirstLoad"];
	}
	return value;
}

- (void)setPageRectsToRect:(NSRect)rect
{
	
}
- (void)copyPagesFrom:(Image *)image
{
	NSArray *pages = [image pagesArray];
	for (Page *page in pages) {
		Page *newpage = [self newPage];
		[newpage setValue:self forKey:@"image"];
		[newpage setPageRect:[page pageRect]];
	}
}

- (void)setOrder:(int)order
{
	[self setPrimitiveValue:[NSNumber numberWithInt:order] forKey:@"order"];
}

- (void)insertNewPageWithRect:(NSRect)imageRect
{
	Page *page = [self newPage];
	[page setValue:self forKey:@"image"];
	[page setPageRect:imageRect];
}

- (void)removePage:(Page *)page
{
	[[self managedObjectContext] deleteObject:page];
}

@end
